<template>
  <!--加上input事件 获取用户输入值 再子传父 -->
  <!-- 增加一个change事件，利用父元素传来的正则表达，进行判断 -->
  <input
    type="text"
    class="myinput"
    @input="handlerinput"
    @change="handlerrules"
    :class="{ success: state.succ, error: state.err }"
  />
</template>

<script>
export default {
  props: {
    rules: {
      type: RegExp,
    },
    msg: {
      type: String,
      default: "输入有误！",
    },
  },
  data() {
    return {
      state: {
        succ: "",
        err: "",
      },
    };
  },
  methods: {
    // 正则判定,如果正则判定为false，输入框底部变红，正确会变绿
    handlerinput(e) {
      let v = e.target.value;
      //   console.log(v);
      this.$emit("input", e.target.value);
      if (v.trim() == "") {
        this.state.succ = false;
        this.state.err = false;
        // return;
        // console.log(this.rules);
      }
      if (this.rules.test(v)) {
        this.state.succ = true;
        this.state.err = false;
      } else {
        this.state.succ = false;
        this.state.err = true;
      }
    },
    handlerrules(e) {
      // 当正则触发弹出msg
      let v = e.target.value;
      if (!this.rules.test(v)) {
        console.log(1);
        this.$toast.fail({ duration: 2500, message: this.msg });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.myinput {
  width: 320 /360 * 100vw;
  height: 50px;
  margin: 15px auto;
  border: 0;
  border-bottom: 2px solid #666;
  outline: 0;
  font-size: 20px;
}
.success {
  border-bottom-color: #38cb1c;
}
.error {
  border-bottom-color: #ff5e61;
}
</style>